#include <iostream>
#include <string>
#include <vector>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "tasks.hpp"

using namespace std;

int processnum=5;

class channel
{
public:
    channel(int wfd,pid_t pid,const string& name)
    :_wfd(wfd)
    ,_pid(pid)
    ,_name(name)
    {;}

public:
    int _wfd;
    pid_t _pid;
    string _name;
};

void worker()
{
    while(1)
    {
        int task;
        int n=read(0,&task,sizeof(int));
        if(n>0)
        {
            vtasks[task]();
        }
        else if(n==0)
        {
            break;
        }
    }
}

void writetask(const vector<channel>& channels)
{
    int cnt=0;
    while(1)
    {
        int task=rand()%vtasks.size();

        int child=rand()%channels.size();

        write(channels[child]._wfd,&task,sizeof(int));

        sleep(2);
    }
}

void quitprocess(const vector<channel>& channels)
{
    for(auto& att:channels)
    {
        close(att._wfd);
    }

    for(auto& att:channels)
    {
        int status;
        waitpid(att._pid,&status,0);
    }
}

int main()
{
    srand(time(NULL));
    //任务
    InitVtasks();

    vector<channel> channels;

    for(int i=0;i<processnum;i++)
    {
        int pipefd[2];
        pipe(pipefd);

        pid_t id=fork();
        if(id==0)
        {
            //子进程
            close(pipefd[1]);
            dup2(pipefd[0],0);
            close(pipefd[0]);
            worker();

            exit(0);
        }

        close(pipefd[0]);
        string name="I'm child:"+to_string(id);
        channels.push_back(channel(pipefd[1],id,name));
    }


    writetask(channels);

    quitprocess(channels);

    return 0;
}